package com.tuton.javanet.chapter01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {
	
	private ServerSocket serverSocket;
	
	private int port = 8000;
	
	public EchoServer()throws IOException {
		this.serverSocket = new ServerSocket(port);
		System.out.println("Server was started....");
	}
	
	
	
	public static void main(String[] args)throws IOException {
		new EchoServer().talk();
	}

	private void talk() throws IOException {
		Socket socket = null;
		try{
			socket = serverSocket.accept();
			System.out.println("A new socket has connected..." +
					socket.getInetAddress()+ ":" +
					socket.getPort());
			BufferedReader br = getReader(socket);
			PrintWriter    pw = getWriter(socket);
			
			String msg = null;
			while((msg = br.readLine())!= null) {
				System.out.println("server-" + msg);
				pw.println(echo(msg));
			}
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try{
				if(socket != null) {
					socket.close();
				}
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	private String echo(String msg) {
		return "Echo: " + msg;
	}



	private PrintWriter getWriter(Socket socket)throws IOException {
		OutputStream socketOut = socket.getOutputStream();
		return new PrintWriter(socketOut,true);
	}

	private BufferedReader getReader(Socket socket) throws IOException {
		InputStream socketIn = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(socketIn));
	}
	
}
